package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.HttpClient;
import com.changgou.service.WeiXinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WeiXinPayServiceImpl
 * @Description
 * @Author 洛尘
 * @Date 18:41 2019/11/26
 * @Version 2.1
 **/
@Service
public class WeiXinPayServiceImpl implements WeiXinPayService {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;



    /**
     *  创建二维码
     * @return
     */
    @Override
    public Map<String, String> createNetive(Map<String, String> parameters) {

        try {
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            Map<String ,String> data = new HashMap<>();

            data.put("appid",appid);                                  //公众账号ID
            data.put("mch_id",partner);                               //商户号
            data.put("nonce_str", WXPayUtil.generateNonceStr());      //随机字符串
            data.put("body","畅购商城");                              //商品描述	body
            data.put("out_trade_no",parameters.get("out_trade_no")); //商户订单号
            data.put("total_fee",parameters.get("total_fee"));       //标价金额
            data.put("spbill_create_ip","127.0.0.1");               //终端IP
            data.put("notify_url",notifyurl);                       //通知地址	notify_url
            data.put("trade_type","NATIVE");                        //交易类型

            //附加数据
            Map<String, String> attachMap = new HashMap<>();
            String username = parameters.get("username");
            String exchange = parameters.get("exchange");
            String routing = parameters.get("routing");
            attachMap.put("username",username);
            attachMap.put("exchange",exchange);
            attachMap.put("routing",routing);
            data.put("attach",JSON.toJSONString(attachMap));

            //将数据转换成xml
            String signedXml = WXPayUtil.generateSignedXml(data, partnerkey);
            //创建HttpClient发送请求
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(signedXml);
            httpClient.post();
            //处理响应数据
            String content = httpClient.getContent();
            //将xml转换成map
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            map.put("out_trade_no", parameters.get("out_trade_no"));
            map.put("total_fee", parameters.get("total_fee"));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 支付状态查询
     * @param out_trade_no
     * @return
     */
    @Override
    public Map<String, String> queryStatus(String out_trade_no) {
        try {
            String url = "https://api.mch.weixin.qq.com/pay/orderquery";
            Map<String ,String> data = new HashMap<>();
            data.put("appid",appid);                                            //公众账号ID	appid	是	String(32)	wxd678efh567hg6787	微信支付分配的公众账号ID（企业号corpid即为此appId）
            data.put("mch_id",partner);                                        //商户号	mch_id	是	String(32)	1230000109	微信支付分配的商户号
            data.put("out_trade_no",out_trade_no);                             //商户订单号	out_trade_no	String(32)	20150806125346	商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|*@ ，且在同一个商户号下唯一。 详见商户订单号
            data.put("nonce_str",WXPayUtil.generateNonceStr());                //随机字符串	nonce_str	是	String(32)	C380BEC2BFD727A4B6845133519F3AD6	随机字符串，不长于32位。推荐随机数生成算法
            String signedXml = WXPayUtil.generateSignedXml(data,partnerkey);   //签名	sign	是	String(32)	5K8264ILTKCH16CQ2502SI8ZNMTM67VS	通过签名算法计算得出的签名值，详见签名生成算法
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(signedXml);
            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            map.put("out_trade_no", out_trade_no);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
